package com.shxc.smarttrade.community.delete;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.just.library.AgentWeb;
import com.just.library.ChromeClientCallbackManager;
import com.just.library.WebDefaultSettingsManager;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.main.MainActivity;
import com.shxc.smarttrade.base.BaseFragment;
import com.shxc.smarttrade.info.Contents;
import com.shxc.smarttrade.utils.Loger;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.shxc.smarttrade.utils.ToastUtils;

import org.xchris.view.annotation.ContentView;
import org.xchris.view.annotation.Event;
import org.xchris.view.annotation.ViewInject;

import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;

/**
 * 社区
 */
@ContentView(R.layout.fragment_community)
public class CommunityFragment extends BaseFragment {

    @ViewInject(R.id.title_textview)
    TextView title_textview;
    @ViewInject(R.id.left_imageview)
    ImageView left_imageview;
    @ViewInject(R.id.linearlayout)
    LinearLayout linearlayout;

    public AgentWeb getmAgentWeb() {
        return mAgentWeb;
    }

    private AgentWeb mAgentWeb;

    private MainActivity mainActivity;

    public static CommunityFragment getInstance(Bundle bundle) {

        CommunityFragment mJsbridgeWebFragment = new CommunityFragment();
        if (mJsbridgeWebFragment != null)
            mJsbridgeWebFragment.setArguments(bundle);
        return mJsbridgeWebFragment;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mainActivity = (MainActivity) getActivity();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mAgentWeb = AgentWeb.with(this)//
                .setAgentWebParent((ViewGroup) view, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))//
                .setIndicatorColorWithHeight(-1, 2)//
                .setWebSettings(WebDefaultSettingsManager.getInstance())
                .setWebChromeClient(mWebChromeClient)
                .setReceivedTitleCallback(mCallback)
                .setSecurityType(AgentWeb.SecurityType.strict)
                .createAgentWeb()//
                .ready()//
                .go(Contents.COMMUNITY_H5);

        //监听js调用本地方法
        if (mAgentWeb != null) {
            mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new AndroidInterface(mAgentWeb, this.getActivity()));
        }
    }

    @Override
    public void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    public void onDestroy() {
        mAgentWeb.clearWebCache();
        mAgentWeb.getWebLifeCycle().onDestroy();
        super.onDestroy();
    }

    private void checkChild() {
        if (!mAgentWeb.getWebCreator().get().canGoBack()) {
            mAgentWeb.back();
            left_imageview.setVisibility(View.GONE);
            mainActivity.changeBottomVisibility(View.VISIBLE);
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String title = (String) msg.obj;
                    if (!title.equals("社区")) {
                        left_imageview.setVisibility(View.VISIBLE);
                        mainActivity.changeBottomVisibility(View.GONE);
                    }else{
                        left_imageview.setVisibility(View.GONE);
                        mainActivity.changeBottomVisibility(View.VISIBLE);
                    }
                    break;
            }
            super.dispatchMessage(msg);
        }
    };

    @Event({R.id.left_imageview})
    private void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_imageview:
                //回退
                if (mAgentWeb.getWebCreator().get().canGoBack()) {
                    mAgentWeb.back();
                }
                checkChild();
                break;
        }
    }


    protected WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //  super.onProgressChanged(view, newProgress);
        }
    };
    protected ChromeClientCallbackManager.ReceivedTitleCallback mCallback = new ChromeClientCallbackManager.ReceivedTitleCallback() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (title_textview != null && !TextUtils.isEmpty(title))
                if (title.length() > 10)
                    title = title.substring(0, 10).concat("...");
            title_textview.setText(title);

            Message msg = new Message();
            msg.obj = title;
            msg.what = 1;
            handler.sendMessage(msg);
        }
    };


    private class AndroidInterface {

        private Handler deliver = new Handler(Looper.getMainLooper());
        private AgentWeb agent;
        private Context context;

        public AndroidInterface(AgentWeb agent, Context context) {
            this.agent = agent;
            this.context = context;
        }
        //调用本地方法 有参
        @JavascriptInterface
        public void callAndroid(final String msg) {
            deliver.post(new Runnable() {
                @Override
                public void run() {
                    Loger.e("msg",msg);
                }
            });
        }

        //调用本地方法 无参
        @JavascriptInterface
        public void chat() {
            deliver.post(new Runnable() {
                @Override
                public void run() {
                    Loger.e("chat","ok");
                    goToChat();
                }
            });
        }
    }

    private void goToChat() {

        if (SpUtils.getInt(mContext, "userId", -1)==-1) {
            ToastUtils.showToast("请先登录");
        }else{
            String chartRoomId = SpUtils.getString(getActivity(), "chartRoomId");
            if (!TextUtils.isEmpty(chartRoomId))
                RongIM.getInstance().startConversation(getActivity(), Conversation.ConversationType.CHATROOM, chartRoomId, "聊天室");
            else
                BaseUtils.showToast("初始化失败", getActivity());
        }
    }

    //连续两次点击后退出应用
    private long firstTime = 0;

    public void cancleSelect() {
        //TODO something
        if (mAgentWeb.getWebCreator().get().canGoBack()) {
            mAgentWeb.back();
        }else{
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                //如果两次按键时间间隔大于2秒，则不退出
                ToastUtils.showToast("再按一次退出程序");
                firstTime = secondTime;
            } else {
                //两次按键小于2秒时，退出应用
                System.exit(0);
            }
        }
    }
}
